//
//  OAuthViewController.swift
//  Weibo
//
//  Created by zxy on 2018/12/6.
//  Copyright © 2018 zxy. All rights reserved.
//

import UIKit
import WebKit
import SVProgressHUD
class OAuthViewController: UIViewController {
    let wb_Appkey = "2695999215"
    let wb_AppSecret = "5c18c1e42988143014355bd80b4fd056"
    let wb_redirect_uri = "http://www.baidu.com"
    override func loadView() {
        super.loadView()
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItem.Style.plain, target: self, action: #selector(close))
        
    //获取未授权页面的url，加载微博登录页面，获取access_Token
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(wb_Appkey)&redirect_uri=\(wb_redirect_uri)"
        let request = URLRequest(url: URL(string: url)!)
        webView.load(request)
        
    }
    
    @objc private func close(){
        dismiss(animated: true, completion: nil)
    }
    
    private lazy var webView: WKWebView = {
        let wv = WKWebView(frame: UIScreen.main.bounds)
        wv.navigationDelegate = self
        return wv
    }()

}

extension OAuthViewController:WKNavigationDelegate{
    //拦截url
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        //微博登录页面:https://api.weibo.com/oauth2/authorize?client_id=2695999215&redirect_uri=http://www.baidu.com
        //微博授权页面:https://api.weibo.com/oauth2/authorize
        //授权成功:http://www.baidu.com/?code=5e79640cb455b5cd5c15c281529228ba
        //取消授权:http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        let url = navigationAction.request.url?.absoluteString
        print(navigationAction.request.url?.absoluteString as Any)
        
        //判断是否是授权回调页面
        //判断字符串是否以xxxxx开头,如果不是以http://www.baidu.com开头说明是授权回调页面
        if !(url?.hasPrefix(wb_redirect_uri))!{
            //allow:允许页面正常加载
            decisionHandler(WKNavigationActionPolicy.allow)
            return
        }
        //判断是否授权成功
        //query:获取url后面的参数，参数如果是以code=开头，说明授权成功
        //因为swift截取字符串方法还不是很成熟，所以转成OC
        let codeStr = (navigationAction.request.url?.query as NSString?)!
        let codeOC:NSString = "code="
        if (codeStr.hasPrefix(codeOC as String)){
            //拿到code,用于第二步调用oauth2/access_token接口，获取授权后的access token
            //拿到access token，就可以获取到用户的数据
            let code = codeStr.substring(from: codeOC.length)
            //调用授权接口获取acessToken
            getAccessToken(code)
        }else{//取消授权，回到自己页面
            close()
        }
        //cancel:不允许页面正常加载,不会跳转到授权回调页面
        decisionHandler(WKNavigationActionPolicy.cancel)
    }
    //调用授权接口获取acessToken
    private func getAccessToken(_ code: String){
        let path = "oauth2/access_token"
        let params = ["client_id":wb_Appkey,
                      "client_secret":wb_AppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":wb_redirect_uri
        ]
        NetworkTools.sharedNetworkTools().post(path, parameters: params, progress: nil, success: { (_, response) in
            if let dict = response,
                let dic = UserAccount.yy_model(with: dict as! [AnyHashable : Any]){
                isLogin = true
                //保存登录成功的用户信息
                userAccount = dic
                self.dismiss(animated: true, completion: nil)
                NotificationCenter.default.post(name: NSNotification.Name("mm"), object: nil)
            }
        }) { (_, error) in
            print(error)
        }
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        SVProgressHUD.setDefaultStyle(.dark)
        SVProgressHUD.show(withStatus: "正在加载中...")
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        SVProgressHUD.dismiss()
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        SVProgressHUD.showError(withStatus: "加载失败")
    }
}
